$(function() {
  //取得地址的参数
  var getParameter = function(name) {
    var search = window.location.search.slice(1); //拿到浏览器的search 去掉问号
    var reg = new RegExp(name + "=(\\w+)", "gi"); // new RegExp  相当于// g:全局  i:不区分大小写
    var searchs = search.match(reg); //匹配字符串  ***=***
    if (searchs) {
      //如果存在
      return searchs[0].slice(name.length + 1);
    }
    return null;
  };

  var getParameter2 = function(index) {
    var search = window.location.pathname.slice(1);
    var searchs = search.split("/");
    if (index < searchs.length) {
      return searchs[index];
    }
    return null;
  };

  //新建文章按钮
  var ul = $(".sidebar ul");
  var essayId = getParameter2(1);
  if (essayId) {
    ul
      .find("a[href='/editor/" + essayId + "']")
      .parent()
      .addClass("active");
  }

  $(".btn-add").on("click", function(e) {
    $.ajax({
      url: "/add-essay",
      method: "post",
      success: function(data) {
        if (data.status == 0) {
          ul.append(
            "<li><a href='/editor/" +
              data.essayId +
              "'>无标题文章</a>" +
              '<span class="btn-del fa fa-times"></span></li>'
          );
        }
      }
    });
  });

  //删除文章的按钮
  $(".btn-del").on("click", function(e) {
    var jThis = $(this);
    var a = jThis.prev("a");
    var href = a.attr("href");
    var essayId = href.slice(8);
    console.log(essayId);
    $.ajax({
      url: "/delete-essay",
      method: "post",
      data: {
        essayId: essayId
      },
      success: function(data) {
        jThis.parent().remove();
        location.href = "/editor";
      }
    });
  });

  //保存文章
  $("#btn-save").on("click", function(e) {
    //阻止默认事件,防止自动提交表单
    e.preventDefault();
    var essayId = $("#essay-id").val();
    var title = $("#essay-title").val();
    var content = $(".simditor-body").html();
    var abstract = $(".simditor-body").text().slice(0,200);

    $.ajax({
      url: "/update-essay",
      method: "post",
      data: {
        essayId: essayId,
        title: title,
        content: content,
        abstract:abstract
      },
      success: function(data) {
        if (data.status == 0) {
          var a = $("a[href='/editor/" + essayId + "']");
          a.text(title);
        }
      }
    });
  });

  // ul.on("click","a",function(e){
  //   //e.preventDefault();
  //   $(this).parent().addClass("active").siblings("li").removeClass("active");
  //   // console.log($(this));

  // })

  if (getParameter2(1)) {
    var editor = new Simditor({
      textarea: $("#editor"),
      upload: {
        url: "/upload-image",
        params: null,
        leaveConfirm: "正在上传文件",
        connectionCount: 3
      }
    });
  }
});
